package com.newenergy.light.ble;

/**
 * Created by granton on 2016/11/11.
 */
public class HeaderHelper {

    static byte[] BENCH_MARKS_LOW = new byte[]{
            0x01, 0x02, 0x04, 0x08,
    };

    static byte[] BENCH_MARKS_HIGH = new byte[]{
            0x10, 0x20, 0x40, (byte) 0x80
    };

    public static int convertHeaders(byte high, byte low) {
        byte[] sources = new byte[]{high, low};
        return convertBytesToInt(sources);
    }



    /**
     * 把若干个字节转换成一个整数
     *
     * @return 整数
     */
    public static int convertBytesToInt(byte[] bytes) {
        int result = 0;
        int length = bytes.length;
        for (int i = 0; i < length; i++) {
            result += convertByteToInt(bytes[i], 2 * i, 16);
        }
        return result;
    }

    private static int convertByteToInt(byte source, int lowOffset, int powerBasic) {
        int sum = 0;

        // 计算低位字节
        int resultLow = 0;
        for (int i = 0; i < BENCH_MARKS_LOW.length; i++) {
            resultLow += (source & BENCH_MARKS_LOW[i]) != 0 ? Math.pow(2, i) : 0;
        }

        // 计算高位字节
        int resultHigh = 0;
        for (int i = 0; i < BENCH_MARKS_HIGH.length; i++) {
            resultHigh += (source & BENCH_MARKS_HIGH[i]) != 0 ? Math.pow(2, i) : 0;
        }

        int highOffset = lowOffset + 1;
        sum = (int) (resultLow * Math.pow(powerBasic, lowOffset) + resultHigh * Math.pow(powerBasic, highOffset));
        // (16^(n+1)) * 高位 + (16^n) * 低位

        return sum;
    }
}